#!/bin/bash
# * =====================================================
# * Copyright © hk. 2022-2025. All rights reserved.
# * File name  : sharedir.sh
# * Author     : 苏木
# * Date       : 2025-10-19
# * Version    : 
# * Description: 
# * ======================================================
##

# 脚本和工程路径
# ========================================================
SCRIPT_NAME=${0#*/}
SCRIPT_CURRENT_PATH=${0%/*}
SCRIPT_ABSOLUTE_PATH=`cd $(dirname ${0}); pwd`
PROJECT_ROOT=${SCRIPT_ABSOLUTE_PATH}/.. # 工程的源码目录，一定要和编译脚本是同一个目录

source "$PROJECT_ROOT/common/common.sh"

# ubuntu20.04挂载共享目录（在ubuntu中手动敲下边的命令）
SHARE_DIR_MOUNT_PATH=/mnt/hgfs
SHARE_DIR_NAME=
SHARED_DIR_PATH=

# 获取共享目录的路径
function share_dir_path_get()
{
    cdi ~
    prt "${PINK}current path         :$(pwd)${CLS}"

    # /mnt/hgfs 目录
    if [ ! -d ${SHARE_DIR_MOUNT_PATH} ];then
        execute mkdir -pv ${SHARE_DIR_MOUNT_PATH}
        execute chmod 777 ${SHARE_DIR_MOUNT_PATH}
        info "${SHARE_DIR_MOUNT_PATH} 路径已创建..."
    else
        info "${SHARE_DIR_MOUNT_PATH} 路径已存在..."
    fi

    # 检查是否有共享文件夹存在
    SHARE_DIR_NAME=$(vmware-hgfsclient)
    if [ -n "${SHARE_DIR_NAME}" ];then
        SHARED_DIR_PATH=${SHARE_DIR_MOUNT_PATH}/${SHARE_DIR_NAME}
        info "shared_dir path is ${SHARED_DIR_PATH}"
    else
        error "被禁止,无法进行后续工作,请检查VMware虚拟机是否开启了共享目录功能"
        return
    fi

    # 开始挂载共享目录
    if [ ! -d ${SHARED_DIR_PATH} ];then
        execute vmhgfs-fuse .host:/ /mnt/hgfs/ -o allow_other # 挂载共享文件夹
    else
       info "${SHARED_DIR_PATH}已挂载... !!!"
    fi
}

# 配置共享目录
function shared_dir_config()
{
    cdi ~
    prt "${PINK}current path         :$(pwd)${CLS}"

    if [ ! -n "${SHARED_DIR_PATH}" ];then
        error "SHARED_DIR_PATH is NULL!!!"
        return
    else
        info "SHARED_DIR_PATH is ${SHARED_DIR_PATH}"
    fi

    local mount_sharedir_path=${SHARE_DIR_MOUNT_PATH}
    local shared_dir_ln[0]=~/01sharedfiles
    local shared_dir_ln[1]=~/桌面/01sharedfiles

    cd ~
    prt "${PINK}current path    :$(pwd)${CLS}"
    prt "${PINK}SHARED_DIR_PATH :${SHARED_DIR_PATH}${CLS}"
    prt "${PINK}SHARED_DIR_NAME :${SHARED_DIR_PATH##*/}${CLS}"
    
    # 创建一些软链接，方便使用
    read -p "是否创建软链接?(默认选择不创建,需要请输入y):" ret
    if [ "${ret}" == "y" ];then
        
        info "创建软链接方便使用..."
        for temp in ${shared_dir_ln[@]}
        do
            if [ -e "${temp}" ];then
                warning "${temp}文件已存在,可以运行命令:【rm ${temp}】,删除后重试!!!"
            else
                ln -s ${SHARED_DIR_PATH} ${temp}
            fi
        done
        for temp in ${shared_dir_ln[@]}
        do
            if [ -L "${temp}" ];then
                info "${temp}软链接可以正常使用!!!"
            else
                error "${temp}软链接无法正常使用!!!"
            fi
        done
    fi
}

share_dir_path_get
shared_dir_config
